//
//  LOCATIONObj.m
//  storeapp
//
//  Created by huangyi on 13-4-7.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "LOCATIONObj.h"

@interface LOCATIONObj () <CLLocationManagerDelegate>

@property(nonatomic,strong)CLLocationManager *manager;

@end

@implementation LOCATIONObj

+(LOCATIONObj*)shared{
    static LOCATIONObj* singleton=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton=[[LOCATIONObj alloc] init];
    });
    return singleton;
}

-(id)init{
    self=[super init];
    if (self) {
        self.manager=[[CLLocationManager alloc] init];
        self.manager.delegate=self;
        self.manager.desiredAccuracy=kCLLocationAccuracyKilometer;
        [self update];
    }
    return self;
}

-(void)update{
    self.location=nil;
    {
        double delayInSeconds = 0.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.manager startUpdatingLocation];
        });
    }
    {
        double delayInSeconds = 20.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.manager stopUpdatingLocation];
        });
    }
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=locations.lastObject;
    float accuracy=location.horizontalAccuracy;
    if (accuracy<manager.desiredAccuracy) {
        if (CLLocationCoordinate2DIsValid(location.coordinate)) {
            NSLog(@"%@",location);
            self.location=location;
            [manager stopUpdatingLocation];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"%@",error.description);
    [manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFinishDeferredUpdatesWithError:(NSError *)error{
    NSLog(@"%@",error.description);
    [manager stopUpdatingLocation];
}

@end
